from wtforms import Form, ValidationError
from wtforms.fields import StringField, IntegerField, FileField
from wtforms.validators import Email, Length, EqualTo, InputRequired
from flask_wtf.file import FileAllowed, FileSize
from models.auth import UserModel
from flask import request
from exts import cache


class BaseForm(Form):
    @property
    def messages(self):
        message_list = []
        if self.errors:
            for errors in self.errors.values():
                message_list.extend(errors)
        return message_list


class RegisterForm(BaseForm):
    # Email 需要 库email_validator
    email = StringField(validators=[Email(message="请输入正确的邮箱!")])
    email_captcha = StringField(validators=[Length(min=6, max=6, message="请输入正确的验证码!")])
    username = StringField(validators=[Length(1, 20, message="请输入正确的用户名")])
    password = StringField(validators=[Length(6, 20, message='请输入正确的密码！')])
    repeat_password = StringField(validators=[EqualTo('password', '两次密码不一致！')])
    graph_captcha = StringField(validators=[Length(min=4, max=4, message="请输入正确的验证码!")])

    def validate_email(self, field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise ValidationError(message="邮箱已存在！")

    def validate_email_captcha(self, field):
        email_captcha = field.data
        email = self.email.data
        cache_captcha = cache.get(email)
        if not cache_captcha or email_captcha != cache_captcha:
            raise ValidationError(message='邮箱验证码错误！')

    def validate_graph_captcha(self, field):
        key = request.cookies.get('_graph_captcha_key')
        cache_captcha = cache.get(key)
        graph_captcha = field.data
        if not cache_captcha or graph_captcha.lower() != cache_captcha.lower():
            raise ValidationError(message="图形验证码错误")


class LoginForm(BaseForm):
    email = StringField(validators=[Email(message="请输入正确的邮箱!")])
    password = StringField(validators=[Length(6, 20, message='请输入正确的密码！')])
    remember = IntegerField()


class UploadForm(BaseForm):
    image = FileField(validators=[FileAllowed(['jpg', 'jpeg', 'png'], message='图片格式要求不符合'),
                                  FileSize(max_size=1024 * 1024 * 5, message='图片太大')])


class EditProfileForm(BaseForm):
    signature = StringField(validators=[Length(min=1, max=200, message='个性签名限制200字')])


class PublicPostForm(BaseForm):
    title = StringField(validators=[Length(max=200, message='标题长度200字以内！')])
    content = StringField(validators=[InputRequired(message='内容不能为空！')])
    board_id = IntegerField(validators=[InputRequired(message='传入板块ID！')])


class PublicCommentForm(BaseForm):
    content = StringField(validators=[InputRequired(message="请输入内容！")])
    post_id = IntegerField(validators=[InputRequired(message="请输入帖子ID！")])
